package com.intelligent.ispc.web.controller;

import com.intelligent.ispc.common.dto.JsonPageResponseDto;
import com.intelligent.ispc.common.dto.JsonResponseDto;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.web.Servlets;
import com.intelligent.ispc.core.dto.RoleDto;
import com.intelligent.ispc.core.entity.Role;
import com.intelligent.ispc.core.service.RoleService;
import com.intelligent.ispc.utils.SystemConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by Rovey.Luo on 2015/10/30.
 */

@Controller
@RequestMapping(value = "/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private SystemConfig systemConfig;

    Integer draw = 0;
    public PageRequest setPageObj(ServletRequest request){
        Integer start = 0;
        if(StringUtils.isNotBlank(request.getParameter("start"))){
            start = Integer.valueOf(request.getParameter("start"));
        }
        Integer size = systemConfig.getPageSize();
        if(StringUtils.isNotBlank(request.getParameter("length"))){
            size = Integer.valueOf(request.getParameter("length"));
        }

        if(StringUtils.isNotBlank(request.getParameter("draw"))){
            draw = Integer.valueOf(request.getParameter("draw"));
        }

        Integer pageNum = 0;
        if((start/size)>0){
            pageNum = start/size;
        }
        return new PageRequest(pageNum,size);
    }
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String nav(Model model,ServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isPermitted("system:role:view")) {
            return "error/noPermission";
        }
        return "role/roleList";
    }

    @ResponseBody
    @RequestMapping(value = "/list")
    public JsonPageResponseDto list(Model model,ServletRequest request){
        try {
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:view")) {
                return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }

            Map<String,Object> searchParam = Servlets.getParametersStartingWith(request,"search_");

            Page<RoleDto> page = roleService.searchRole(searchParam,setPageObj(request));
            List<RoleDto> roles1 = page.getContent();
            JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(roles1);
            json.setRecordsTotal(page.getTotalElements());
            json.setRecordsFiltered(page.getTotalElements());
            json.setDraw(draw);

            return  json;
        } catch (Exception e) {
            return JsonPageResponseDto.FAILURE().setMessage(e.getMessage());
        }
    }

    @RequestMapping(value = "register",method =RequestMethod.GET)
    public String registerForm(Model model){

        Subject subject = SecurityUtils.getSubject();
        if(!subject.isPermitted("system:role:create")) {
            return "error/noPermission";
        }

        return "role/createRole";
    }
    @ResponseBody
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public JsonResponseDto register(RoleDto roleDto, Model model){
        try{
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:create")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }
            roleService.saveRole(roleDto);
            return JsonResponseDto.SUCCESS();
        } catch (ApplicationException ex){
            return JsonResponseDto.FAILURE().setMessage(ex.getMessage());
        }
    }

    @RequestMapping(value = "find",method = RequestMethod.POST)
    public JsonResponseDto find(Model model){
        try {
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:view")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }
            List<RoleDto> roleDto = roleService.findAllRoles();

            return JsonResponseDto.SUCCESS().setBody(roleDto);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
    }

    @RequestMapping(value = "edit/{id}",method = RequestMethod.GET)
    public String editForm(@PathVariable("id") String id,Model model){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isPermitted("system:role:edit")) {
            return "error/noPermission";
        }
        RoleDto roleDto = roleService.findById(id);
        model.addAttribute("role",roleDto);
        return "role/editRole";
    }

    @ResponseBody
    @RequestMapping(value = "update{id}",method = RequestMethod.GET)
    public JsonResponseDto updateForm(@PathVariable("id") String id,Model model){
        try {
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:view")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }
            return JsonResponseDto.SUCCESS().setBody(roleService.findById(id));
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "update",method = RequestMethod.POST)
    public JsonResponseDto update(@ModelAttribute("role") RoleDto roleDto,Model model){
        try {
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:edit")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }
            roleService.updateRole(roleDto);
            return JsonResponseDto.SUCCESS();
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "delete/{id}")
    public JsonResponseDto delete(@PathVariable("id") String id,Model model){
        try{
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isPermitted("system:role:delete")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }

            roleService.deleteRole(id);
            return JsonResponseDto.SUCCESS();
        } catch (ApplicationException ex){
            return JsonResponseDto.FAILURE().setMessage(ex.getMessage());
        }
    }

    @ModelAttribute
    public void getUser(@RequestParam(value = "id",defaultValue = "") String id,Model model){
        if(StringUtils.isNotBlank(id)){
            model.addAttribute("role",roleService.findById(id));
        }
    }
}
